package com.systop.common.modules.area.service;

import java.util.List;

import org.springframework.stereotype.Service;

import com.systop.common.modules.area.AreaUtil;
import com.systop.common.modules.area.model.Area;
import com.systop.core.service.BaseGenericsManager;

@Service
public class AreaManager extends BaseGenericsManager<Area> {

	/**
	 * 如果parent为空则返回省级地区
	 * 
	 * @param parent
	 * @return
	 */
	public List<Area> getAreas(String parent) {
		String hql = null;
		if (parent == null || "0".equals(parent)) {// 将要查询市级
			hql = "from Area a where a.parent is null order by a.id";
			return query(hql);
		} else {
			hql = "from Area a where a.parent = ? order by a.id";
			return query(hql, parent);
		}
	}
	
	/**
	 *  获得地区全面 省 市 区县
	 * @param code
	 * @return
	 */
	public String getAllAreaName(String code){
		if (code == null){
			return "";
		}
		Area county = null;
		Area city = null;
		Area province = null;
		if (AreaUtil.isProvince(code)){//省级
			province = getAreaByCode(code);
		}else if (AreaUtil.isCity(code)){
			city = getAreaByCode(code);
			if (city != null){
				province = getAreaByCode(city.getParent());
			}
		}else{//区县级代码
			county = getAreaByCode(code);
			if (county != null){
				city = getAreaByCode(county.getParent());
				province = getAreaByCode(city.getParent());
			}
		}
		
		StringBuffer allName = new StringBuffer();
		if (province != null){
			allName.append(province.getName());
		}
		if (city != null){
			allName.append(" ").append(city.getName());
		}
		if (county != null){
			allName.append(" ").append(county.getName());
		}
		return allName.toString();
	}
	
	public Area getAreaByCode(String code){
		if (code != null){
			String hql = "from Area a where a.code = ?";
			return findObject(hql, code);
		}else{
			return null;	
		}
	}
	
	
	public String getAreaName(String code){
		String hql = "from Area a where a.code = ?";
		Area a = findObject(hql, code);
		return (a != null) ? a.getName() : "";
	}

}
